package com.agriculture.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

public class AESUtil {

    // 指定加密算法
    private static final String ALGORITHM = "AES";

    // 必须是 16/24/32 字节长度的密钥，这里仅作示例
    private static final String KEY = "1234567890123456";

    /**
     * 加密
     * @param value 原始字符串
     * @return 加密后字符串(Base64编码)
     */
    public static String encrypt(String value) {
        try {
            Key key = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedBytes = cipher.doFinal(value.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("加密过程出现错误", e);
        }
    }

    /**
     * 解密
     * @param encryptedValue Base64 编码后的加密字符串
     * @return 解密后字符串
     */
    public static String decrypt(String encryptedValue) {
        try {
            Key key = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedValue);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("解密过程出现错误", e);
        }
    }
}
